package com.javajun.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.javajun.custom.BaseService;
import com.javajun.entity.BookBorrow;
import com.javajun.form.BookBorrowForm;
import com.javajun.repository.BookRepository;

@Service
public class BookBorrowService extends BaseService<BookBorrow, Integer>{

    @Autowired
    private BookRepository bookRepository;
    
    public String getNowTime() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public Specification<BookBorrow> buildSpec(BookBorrowForm form) {

        Specification<BookBorrow> specification = new Specification<BookBorrow>() {
            
            @Override
            public Predicate toPredicate(Root<BookBorrow> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                HashSet<Predicate> rules=new HashSet<>();
                String name = form.getName();
                if(StringUtils.hasText(name)) {
                    rules.add(cb.like(root.get("name"), "%"+name+"%"));
                }
                String state = form.getState();
                if(StringUtils.hasText(state)) {
                    rules.add(cb.equal(root.get("state"), state));
                }
                String username = form.getUsername();
                if(StringUtils.hasText(username)) {
                    rules.add(cb.equal(root.get("sysUser").get("username"), username));
                }
                return cb.and(rules.toArray(new Predicate[rules.size()]));
            }
        };
        return specification;
    }
    
}
